package com.example.demo.tool;

/**
 * 七牛云上传工具
 */
import com.google.gson.Gson;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component //把当前类托管给Spring，其他地方调用kodo,得通过resource
public class KoDoTool {
    @Value("${project.kodoak}") //@Value可以从yml中获取数据
    private String ak; //七牛云个人ak
    @Value("${project.kodosk}")
    private String sk; //七牛云个人sk
    @Value("${project.kodobucketname}")
    private String bucketName; //七牛云桶名
    @Value("${project.kodourl}")
    private String bucketUrl;  //七牛云桶URL

    /**
     * 上传本地文件到七牛云
     * @param filePath 本地文件路径
     * @return 七牛云链接地址
     */
    public String UploadFileToKoDo(String filePath){
        String fileName = UUID.randomUUID().toString()+"."+filePath.split("\\.")[1];
        try{
                Configuration configuration = new Configuration(Region.huadong());//Region.huadong():表示你的空间地址在华东
                UploadManager uploadManager = new UploadManager(configuration);//新建上传管理
                Auth auth = Auth.create(ak,sk);//新建令牌
                String token = auth.uploadToken(bucketName);//获取上传token
                Response response = uploadManager.put(filePath,fileName,token);//上传文件并获取结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);//解析结果
                return "http://"+bucketUrl+"/"+fileName;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }


}
